<template>
  <md-page title="" :showLeft="false">
    <view class="container">
      <!-- 头部头像及名称 -->
      <md-icon :url="data.myInfo?.my_top_img" width="690" height="380" @click="handleHead">
        <view class="my-top-content">
          <md-icon type="bg" radius="100" :url="data.myInfo?.avatar" name="my_head" width="130" height="130" />
          <md-icon :url="data.go_login_icon" width="284" height="48" class="m-top-10">
            <view class="my-title">{{ data.myInfo?.mobile || '去登录' }}</view>
          </md-icon>
        </view>
      </md-icon>
      <!-- 了解我们 -->
      <view class="m-top-20" @click="handleAbout">
        <md-icon :url="data.myInfo?.my_middle_img" width="690" height="180" />
      </view>
      <!-- 我的积分 -->
      <view class="points-card card-wrap" @click="handleJumpPoints">
        <view class="title">我的积分</view>
        <view class="points-value-wrap">
          <view class="points-value" :style="{ color: data.configInfo.select_color_text || '#ff9802' }">
            {{ data.myInfo?.score || 0 }}
          </view>
        </view>
      </view>
      <!-- 我的优惠券 -->
      <view class="coupon card-wrap">
        <view class="title">我的优惠券</view>
        <view class="item-wrap flex-b">
          <view
            class="item"
            v-for="(item, index) in data.coupons"
            :key="item.value"
            @click="() => handleJumpCoupon(index)">
            <view class="count" :style="{ color: data.configInfo.select_color_text }">
              {{ data.myInfo?.[item.value] || 0 }}
            </view>
            <view class="name">{{ item.text }}</view>
          </view>
        </view>
      </view>
      <!-- 常用功能 -->
      <view class="common-use card-wrap">
        <view class="title">常用功能</view>
        <uni-grid :column="3" :show-border="false" :square="false" @change="gridChange">
          <uni-grid-item v-for="(item, index) in data.list" :index="index" :key="index">
            <view class="grid-item-box">
              <md-icon :url="item.img" width="54" height="54"></md-icon>
              <text class="text">{{ item.name }}</text>
            </view>
          </uni-grid-item>
          <!-- <uni-grid-item v-for="(item, index) in data.testList" :index="data.list.length + index" :key="data.list.length + index">
            <view class="grid-item-box">
              <md-icon :url="item.img" width="54" height="54"></md-icon>
              <text class="text">{{ item.name }}</text>
            </view>
          </uni-grid-item> -->
        </uni-grid>
      </view>
    </view>
  </md-page>
  <!-- 底部导航 -->
  <bottom-tab-bar :selected="4" />
</template>

<script setup lang="ts">
import { myIndex } from '@/api';
import type { Common } from '@/api/data';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { reactive } from 'vue';

const data = reactive<any>({
  testList: [
    // { id: 'x1', name: 'AR打卡', img: 'https://img.yzcdn.cn/vant/apple-1.jpg', link: '/pages/ar/ar-checkin' },
    // { id: 'x2', name: '举报', img: 'https://img.yzcdn.cn/vant/apple-2.jpg', link: '/pages/report/index' },
    // { id: 'x3', name: '壁纸下载', img: 'https://img.yzcdn.cn/vant/apple-3.jpg', link: '/pages/nfc/background?poster_id=K1xnCJ8UMnOHoomk' }
  ],
  list: [],
  myInfo: {},
  coupons: [
    { text: '抽奖券', value: 'raffle_ticket' },
    { text: '奖品券', value: 'prize_ticket' },
    { text: '报名券', value: 'signup_ticket' },
  ],
  go_login_icon: '',
  configInfo: {}, // 全局配置信息
});

const gridChange = (e: any) => {
  let { index } = e.detail;
  const item = data.list[index];
  console.log(item);
  let url = item.link;
  if (url) {
    uni.navigateTo({
      url,
    });
  } else {
    // 联系客服 \n 模拟器不支持，但是真机可以
    if (item.name === '联系客服') {
      uni.showModal({
        title: '客服电话',
        content: (data.myInfo?.kefu_mobile || '') + '\n' + '【' + data.myInfo?.kefu_worktime + '】',
        confirmText: '呼叫',
        success: res => {
          if (res.confirm) {
            uni.makePhoneCall({
              phoneNumber: data.myInfo?.kefu_mobile || '',
            });
          }
        },
      });
    } else if (['扫码打卡', '商户核销'].includes(item.name)) {
      // 扫码
      handleScanCode();
    } else {
      uni.showToast({
        title: '功能暂未开放',
      });
    }
  }
};

const handleHead = () => {
  if (data?.myInfo?.mobile) {
    // 跳转个人信息
    uni.navigateTo({
      url: '/pages/other/userinfo?info=' + JSON.stringify(data.myInfo),
    });
    return;
  }
  // 跳转登录页面
  uni.navigateTo({
    url: '/pages/login/index',
  });
};

// 跳转券
const handleJumpCoupon = (index: number) => {
  const item = data.coupons[index];
  uni.navigateTo({
    url: `/pages/other/coupon/index?type=${item.value}&title=${item.text}`,
  });
};

// 跳转到关于我们
const handleAbout = () => {
  uni.navigateTo({
    url: '/pages/my/about',
  });
};

// 跳转到积分详情
const handleJumpPoints = () => {
  uni.navigateTo({
    url: '/pages/other/points/my',
  });
};

const handleScanCode = () => {
  // 允许从相机和相册扫码
  uni.scanCode({
    success: function (res) {
      console.log('条码类型：' + res.scanType);
      console.log('条码内容：' + res.result);
      let url = res.result;
      if (url) {
        url = decodeURIComponent(url);
        uni.navigateTo({
          url,
        });
      }
    },
  });
};

/**
 * 接口相关
 */

const fetchMyIndex = async () => {
  uni.showLoading({
    title: '加载中',
  });
  try {
    const res = await myIndex();
    data.myInfo = res.data;
    // 我的菜单列表
    const myIcons: Common.BottomIcon.DataType[] = uni.getStorageSync('myIcons')
      ? JSON.parse(uni.getStorageSync('myIcons'))
      : [];
    data.list = myIcons
      .filter(item => {
        // is_volunteer 自愿者 或 is_merchant 商家 可打开扫码打卡
        if (res.data?.is_volunteer == 1 || res.data?.is_merchant == 1) {
          return true;
        }
        return !['扫码打卡', '商户核销', '核销记录'].includes(item.name);
      })
      .concat(data.testList);
    if (data.myInfo.mobile && (!data.myInfo.username || !data.myInfo.avatar)) {
      // 如果是已登录且没有设置过用户名或者头像跳转个人信息
      uni.navigateTo({
        url: '/pages/other/userinfo?info=' + JSON.stringify(data.myInfo) + '&isForce=1',
      });
      return;
    }
  } catch (error) {}
  uni.hideLoading();
};

onLoad(() => {
  // 跳转润无声按钮处理
  const configInfo = uni.getStorageSync('configInfo');
  if (Object.keys(configInfo || {})?.length > 0) {
    const parseInfo = JSON.parse(configInfo);
    data.configInfo = parseInfo;
  }
});

onShow(() => {
  fetchMyIndex();

  const configInfo = uni.getStorageSync('configInfo') ? JSON.parse(uni.getStorageSync('configInfo')) : '';
  if (configInfo) {
    data.go_login_icon = configInfo.go_login_icon;
  }
});
</script>
<style lang="scss" scoped>
.container {
  padding: 30rpx;
  padding-bottom: calc($safe-bottom + 80px + 20rpx);
  .my-top-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding-top: 70rpx;
    .my-title {
      line-height: 48rpx;
      text-align: center;
      font-size: 30rpx;
      color: white;
    }
  }

  .card-wrap {
    padding: 0 26rpx 22rpx;
    box-sizing: border-box;
    .title {
      font-size: 34rpx;
      color: $title;
      font-weight: bold;
      height: 90rpx;
      line-height: 90rpx;
      border-bottom: 1rpx solid #ededed;
    }
  }
  .points-card {
    width: 690rpx;
    background: #ffffff;
    border-radius: 20rpx;
    margin-top: 20rpx;
    cursor: pointer;
    transition: all 0.3s ease;
    &:active {
      opacity: 0.95;
      transform: scale(0.98);
    }
    .points-value-wrap {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 30rpx 0;
      .points-value {
        font-size: 56rpx;
        font-weight: bold;
        line-height: 1.2;
        text-align: center;
      }
    }
  }
  .coupon {
    width: 690rpx;
    height: 219rpx;
    background: #ffffff;
    border-radius: 20rpx;
    margin-top: 20rpx;
    .item-wrap {
      padding: 0 30rpx;
      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 20rpx;
        .count {
          // color: $primary;
          font-weight: bold;
          font-size: 40rpx;
        }
      }
    }
  }
  .common-use {
    width: 690rpx;
    // min-height: 520rpx;
    background: #ffffff;
    border-radius: 20rpx;
    margin-top: 20rpx;
    .grid-item-box {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 15px 0;
    }
  }
}
</style>
